package org.jecat.pusher;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

public class Session {

	private SelectionKey m_key;
	private Request m_req;

	public Session(SelectionKey key,Request req)
	{
		m_key = key ;
		m_req = req ;
		
		m_key.attach(this) ;
	}
	public SelectionKey nioSelectionKey() 
	{
		return m_key ;
	}
	public Request request() 
	{
		return m_req ;
	}
	public String channelName() 
	{
		return m_req==null? null: m_req.get("channel", null) ;
	}
	public String id() 
	{
		return m_req==null? null: m_req.get("id", null) ;
	}
	public SocketChannel socket()
	{
		return m_key==null? null: (SocketChannel)m_key.channel() ;
	}
	public Boolean requestFinished()
	{
		return m_req==null? null: m_req.avalid() ;
	}

	public static Session getSession(SelectionKey key)
	{
		Session session = (Session)key.attachment() ;
		if(session==null)
		{
			session = new Session(key,new Request()) ;
			key.attach(session) ;
		}
		
		return session ;
	}
	public void destroy()
	{
		if( socket().isConnected() )
		{
			if(m_key!=null)
			{
				m_key.cancel() ;
			}
			
			try {
				socket().close() ;
			} catch (IOException e) {
				Server.log(e.getMessage()) ;
			}
		}

		if(m_key!=null)
		{
			m_key.attach(null) ;
		}
		m_key = null ;
		m_req = null ;
	}
}
